package com.uchengwang.ui.cm_ui.ucity.ui;

import android.Manifest;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.uchengwang.R;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.ui.base_ui.ui.BaseWithTitleActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.me.presenter.HttpUserManager;
import com.uchengwang.ui.cm_ui.ucity.adapter.MobileAdapter;
import com.uchengwang.ui.listener.PermissionsListener;
import com.uchengwang.ui.utils.CheckUtil;
import com.uchengwang.ui.utils.PermissionUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by U城网 on 2018/2/9.
 * 手机联系人
 */

public class MobileContactActivity extends BaseWithTitleActivity{
    private RecyclerView recycleView;
    private MobileAdapter adapter;
    private ContentResolver cr;
    private List<UserBean> mobileList;
    private List<String> mobilePhones;

    private String[] phones;
    private List<UserBean> chooses, follows;//最终选择的  关注的和好友

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_jifen);
        setTitle("手机联系人");

        initView();
    }

    private void initView() {
        recycleView = (RecyclerView) findViewById(R.id.rv);
        initData();
    }

    private void initData() {
        adapter = new MobileAdapter(this);
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.setAdapter(adapter);

        PermissionUtils.getUtils().requestPermissions(this, "该功能缺少权限", new PermissionsListener() {
            @Override
            public void onSuccess() {
                getMobile();
            }

            @Override
            public void onFailed() {
                UCommonUtil.getUtil().showToast(MobileContactActivity.this, "缺少权限");
            }
        }, Manifest.permission.READ_CONTACTS);


    }

    //拿到手机里的额联系人
    private void getMobile(){
        //定义一个接收联系人姓名和电话号码的集合
        mobileList = new ArrayList<>();
        mobilePhones = new ArrayList<>();

        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        //向下移动光标
        while(cursor.moveToNext()){
            //取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String contactName = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);

            String phoneNumber ="";

            while(phone != null && phone.moveToNext()) {
                phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                //格式化手机号
                phoneNumber = phoneNumber.replace("-","");
                phoneNumber = phoneNumber.replace(" ","");
            }
            if (!TextUtils.isEmpty(contactName) && !TextUtils.isEmpty(phoneNumber) && CheckUtil.getChecker().checkTelNum(phoneNumber)){
                //将用户名和号码放入Map集合中
                UserBean bean = new UserBean();
                bean.setRealName(contactName);
                bean.setMobile(phoneNumber);
                Log.d("jjf", "姓名="+contactName+"==手机号=="+phoneNumber);
                mobilePhones.add(phoneNumber);
                mobileList.add(bean);
            }
        }

        initHttpData();
    }

    /**
     * 拿到手机号后 后台匹配
     * */
    private void initHttpData(){
        if (mobilePhones != null && mobilePhones.size() >0){
            int size = mobilePhones.size();
            phones = new String[size];
            for (int i=0; i<size; i++){
                phones[i] = mobilePhones.get(i);
            }

            HttpUserManager.getManager().getContacts(this, phones, new OnHttpResultListener<UserBean>() {
                @Override
                public void onResult(int status, String msg, int total, List<UserBean> list) {
                    if (list != null){
                        if (chooses == null){
                            chooses = new ArrayList<UserBean>();
                            follows = new ArrayList<UserBean>();
                        }else {
                            chooses.clear();
                            follows.clear();
                        }
                        //遍历本地的手机联系人 设置注册信息
                        for (UserBean bean :list){
                            for (UserBean b: mobileList){
                                if (bean.getMobile().equals(b.getMobile())){
                                    //本地手机号注册了
                                    b.setFollow(bean.isFollow());
                                    b.setFriend(bean.isFriend());
                                    b.setRemarkName(bean.getRemarkName());
                                    b.setNickName(bean.getNickName());
                                    b.setUserAvatar(bean.getUserAvatar());
                                    b.setId(bean.getId());

                                    if (bean.isFollow() || bean.isFriend()){
                                        //自己关注了 或者是好友的 放在最后
                                        follows.add(b);
                                    }else {
                                        chooses.add(b);
                                    }
                                }
                            }
                        }
                        mobileList.removeAll(chooses);
                        mobileList.removeAll(follows);
                        chooses.addAll(mobileList);
                        chooses.addAll(follows);
                        adapter.setData(chooses);
                    }
                }
            });


        }
    }
}
